// pages/photoAlbum/photoAlbum.js
const db = wx.cloud.database(); // 获取云数据库引用
const photosCollection = db.collection('photos'); // 获取照片信息集合的引用

Page({
  data: {
    photoFolders: [],
    currentAlbum: null,
    userId: '' // 存储当前用户ID
  },

  onLoad: function() {
    this.getUserId(); // 页面加载时获取用户ID
  },

  getUserId: function() {
    const userId = wx.getStorageSync('userId');
    console.log('获取到的用户ID:', userId); // 调试日志
    if (userId) {
      this.setData({ userId: userId });
      this.getClassifiedPhotos(userId); // 加载当前用户的照片数据
    } else {
      wx.showToast({
        title: '未能获取用户ID',
        icon: 'none'
      });
    }
  },

  getClassifiedPhotos: function(userId) {
    const that = this;
    photosCollection.where({
      userId: userId
    }).get().then(res => {
      console.log('Raw photos data from database:', res.data); // 打印数据库查询结果
      // 检查每条数据是否完整
      res.data.forEach((photo) => {
        if (!photo.location || !photo.location.city) {
          console.error('不完整的照片数据:', photo);
        }
      });
      let photoFolders = groupPhotosByCity(res.data);
      that.setData({
        photoFolders: photoFolders
      });
      console.log('photoFolders after setData:', that.data.photoFolders); // 打印setData后的数据
    }).catch(err => {
      console.error('Error fetching photos:', err);
    });
  },

  openAlbum: function(e) {
    const index = e.currentTarget.dataset.index;
    if (index >= 0 && index < this.data.photoFolders.length) {
      const currentAlbum = this.data.photoFolders[index];
      this.setData({
        currentAlbum: currentAlbum
      });
      wx.navigateTo({
        url: `/pages/photo/photo?album=${JSON.stringify(currentAlbum)}`
      });
    } else {
      console.error('Index out of range');
    }
  },

  navigateToLocation: function(e) {
    const index = e.currentTarget.dataset.index;
    const photoFolder = this.data.photoFolders[index];
    const photo = photoFolder.photos[e.currentTarget.dataset.photoIndex]; // 获取当前点击的照片对象
    console.log('Photo folder at index', index, 'with photo:', photo); // 打印调试信息
    if (photo && photo.location && photo.location.latitude && photo.location.longitude) {
      wx.openLocation({
        latitude: parseFloat(photo.location.latitude),
        longitude: parseFloat(photo.location.longitude),
        scale: 18,
        success: function() {
          console.log('导航成功');
        },
        fail: function(err) {
          console.error('导航失败:', err);
        }
      });
    } else {
      wx.showToast({
        title: '位置信息不完整',
        icon: 'none',
      });
    }
  }
});

function groupPhotosByCity(photos) {
  let folders = {};
  photos.forEach((photo) => {
    // 检查 photo.location 和 photo.location.city 是否存在
    if (photo.location && photo.location.city) {
      const city = photo.location.city;
      if (!folders[city]) {
        folders[city] = {
          location: { ...photo.location },
          photos: [],
          uniqueKey: city
        };
      }
      folders[city].photos.push({
        fileID: photo.fileID,
        description: photo.description,
        location: { ...photo.location }
      });
    } else {
      console.error('照片数据不完整:', photo);
    }
  });
  return Object.values(folders);
}
